<?php
/**
 * Uploader
 *
 * PHP versions 5
 *
 * LICENSE:
 * 
 * This library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General
 * Public License as published by the Free Software Foundation;
 * either version 2.1 of the License, or (at your option) any
 * later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * @category  Uploader
 * @package   BAZALT/Uploader
 * @author    Alex Slubsky <aslubsky@gmail.com>
 * @license   http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @version   $Revision: 90 $
 * @link      http://www.php-solves.com/
 */
 
 /**
 
         print '<form enctype="multipart/form-data" name="test" action="/" method="POST">
        <input type="file" name="bzlt_file">
        <input type="submit">
        </form>';
        using('Framework.System.Uploader');
        $up = new Uploader();
        $up->setUploadDir( 'W:\home\bazalt.ua\projects\bazalt\www\tmp' );
        $up->upload();
 */
 
 
/**
 * Uploader
 *
 * @category Uploader
 * @package  BAZALT/Uploader
 * @author   Alex Slubsky <aslubsky@gmail.com>
 * @license  http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @version  $Revision: 90 $
 * @link     http://www.php-solves.com/
 */
class UploaderWidget extends AbstractWidget implements IWebConfig
{
    /**
     * 
     */  
    const FILE_EXTS   = 'jpg,jpeg,png,gif';
    
    /**
     * 
     */  
    const FILE_MAX_SIZE   = 2000000;//2MB
    
    protected static $fileExts = self::FILE_EXTS;
    
    protected static $fileMaxSize = self::FILE_MAX_SIZE;
    
    protected static $uploadDir = null;
    
    protected static $dataModel = 'File';
    
    public function __construct( $params = null  )
    {
        /*$obj = new $dataModel();
        if (!getType($obj)->hasInterface('IUploader')) {
            throw new InterfaceException('IUploader');
        }*/
        
        parent::__construct( $params );
    }
    
    public function loadWebConfig(SimpleXMLElement $elem)
    {
        $fileExts = (string)$elem->attributes()->fileExts;
        $fileMaxSize = (string)$elem->attributes()->fileMaxSize;
        $uploadDir = (string)$elem->attributes()->uploadDir;

        if ($fileExts) {
            self::$fileExts = $fileExts;
        }

        if ($fileMaxSize) {
            self::$fileMaxSize = $fileMaxSize;
        }
        
        if ($uploadDir) {
            self::$uploadDir = $uploadDir;
        }        
    }
    
    public function setUploadDir( $uploadDir )
    {
        self::$uploadDir = $uploadDir;
    }
    
    public function setDataModel( $dataModel )
    {
        self::$dataModel = $dataModel;
    }    
    
    public function upload()
    {
        //auth and ACL checking
        
        /*$file= new File();        
        $file->title = addslashes($this->params['title']);
        $file->owner = $user->id;*/

        try
        {
            //print 'f:'; print_r($_FILES);
        
            $fileName = md5(rand());
            
            $fileName = $this->uploadFile( $fileName );print'<br/>';
            
            print 'Good sup - '.$fileName;
         }
        catch (Exception $e) 
        {
            print $e->getMessage();
        }                 
       /* 
        $file->save();

        $res = array( 'id' => $file->id, 'title' => $file->title, 'filename' => $fname, 'url' => $file->url, 'type' => $uType );
        //fb($arr);
        return  $this->buildResponse( $res, 200 );*/
    }
    
    private function checkFolder( $path )
	{
        if( file_exists( $path ) ) 
            return;

        mkdir( $path , 0777, true);
    }
    
    public function uploadFile( $fileName )
    {
        $file = current( $_FILES );
        if ($file['error'] !== UPLOAD_ERR_OK) {
            throw new UploaderException($file['error']);
        }

        if( is_null( self::$uploadDir ) ) {
            throw new Exception('Upload dir is not set');
        }
        //$this->uploadDir = 'W:/tmp/';
        $storageDir = self::$uploadDir . DIRECTORY_SEPARATOR . $fileName[0] . DIRECTORY_SEPARATOR . $fileName[1];
        
        $this->checkFolder( $storageDir );
        
        //check
        $file['ext'] = strtolower( end(explode('.', $file['name'] )) );
        if( !$this->isFileValid( $file ) ) {
            throw new Exception ( 'File is not vaild' );
        }        
        
        //move to storage
        $fileName .= '.' . $file['ext'];
        move_uploaded_file( $file['tmp_name'], $storageDir . DIRECTORY_SEPARATOR . $fileName );
        
        //return file info
        return $fileName;
    }
    
    public function isFileValid( $fileInfo )
    {
        $valid = true;
        if( intval($fileInfo['size']) > self::$fileMaxSize ) {
            $valid = false;
        }
        
        $exts = explode( ',', self::$fileExts );
        if( !in_array( $fileInfo['ext'], $exts ) ) {
            $valid = false;
        }
       
        return $valid;
        /*
        $imageinfo = getimagesize($fileInfo['tmp_name']);
        */
    }    

    public function display()
    {
        return $this->render('tpl/uploader.tpl');
    }
}